<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Rate
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: Reviews.php 2010-07-02 19:53 michael $
 * @author     Michael
 */

/**
 * @category   Application_Extensions
 * @package    Rate
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Rate_Model_DbTable_Pagereviews extends Engine_Db_Table {
	protected $_rowClass = 'Rate_Model_Pagereview';
	
	public function getPaginator($page_id, $user_id, $page = 1) {
		
		$tbl_vote = Engine_Api::_ ()->getDbTable ( 'votes', 'rate' );
		
		$select = $this->select ()->setIntegrityCheck ( false )->from ( array ('r' => $this->info ( 'name' ) ), new Zend_Db_Expr ( 'r.*, IF(r.user_id=' . ( int ) $user_id . ',1,0) AS `is_owner`' ) )->joinLeft ( array ('v' => $tbl_vote->info ( 'name' ) ), new Zend_Db_Expr ( 'v.review_id = r.pagereview_id' ), new Zend_Db_Expr ( 'AVG(v.rating) AS rating' ) )->where ( 'r.page_id = ?', $page_id )->group ( 'r.pagereview_id' )->order ( 'is_owner DESC' )->order ( 'r.creation_date DESC' );
		
		$paginator = Zend_Paginator::factory ( $select );
		$paginator->setItemCountPerPage ( 10 );
		$paginator->setCurrentPageNumber ( $page );
		
		return $paginator;
	
	}
	
	public function isAllowedPost($page_id, $viewer) {
		
		if ($viewer->getIdentity ()) {
			$is_permission = Engine_Api::_ ()->getDbtable ( 'permissions', 'authorization' )->getAllowed ( 'rate', $viewer->level_id, 'reviewcreate' );
			$select = $this->select ()->where ( 'user_id = ?', $viewer->getIdentity () )->where ( 'page_id = ?', $page_id );
			$is_post = ( bool ) $select->query ()->rowCount ();
			return ($is_permission && ! $is_post);
		}
		return false;
	}
	
	public function getScore($item_id) {
		
		// is review types
		$tbl_field = Engine_Api::_ ()->fields ()->getTable ( 'page', 'values' );
		$select = $tbl_field->select ()->from ( $tbl_field->info ( 'name' ), 'value' )->where ( 'item_id = ?', $item_id );
		
		$category_id = $tbl_field->getAdapter ()->fetchOne ( $select );
		
		$tbl_type = Engine_Api::_ ()->getDbTable ( 'types', 'rate' );
		$is_types = ( bool ) $tbl_type->select ()->where ( 'category_id = ?', $category_id )->query ()->rowCount ();
		if (! $is_types) {
			return false;
		}
		
		$tbl = Engine_Api::_ ()->getDbTable ( 'votes', 'rate' );
		$select = $tbl->select ()->from ( $tbl->info ( 'name' ), new Zend_Db_Expr ( 'SUM(rating) AS rating, COUNT(*) AS total' ) )->where ( 'page_id = ?', $item_id );
		
		$row = $tbl->getAdapter ()->fetchRow ( $select );
		
		$item_score = $count = 0;
		
		if ($row) {
			
			$item_score = ($row ['rating']) ? round ( $row ['rating'] / $row ['total'], 2 ) : 0;
			
			$count = $this->select ()->where ( 'page_id = ?', $item_id )->query ()->rowCount ();
		}
		
		return array ('item_score' => $item_score, 'count' => $count );
	
	}

}